using Abp.Domain.Repositories;
using Abp.EntityFrameworkCore.Repositories;
using Abp.Extensions;
using Abp.Timing;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Authorization.Users;
using SOEI.Solution.Customized;
using SOEI.Solution.DomainEntities.Parameters.DomainService;
using SOEI.Solution.Helper;
using SOEI.Solution.Integratedes.ElectronicSignet;
using SOEI.Solution.Integratedes.ElectronicSignet.DomainService;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace SOEI.Solution.Integratedes.Organization.DomainService
{
	/// <summary>
	/// 领域服务层一个模块的核心业务逻辑
	///</summary>
	public class OEconomyPersonManager : DomainServiceBase, IOEconomyPersonManager
	{
		// 机构人员仓储
		private readonly IRepository<OEconomyPerson, string> _oeconomypersonRepository;
		// 机构管理仓储
		private readonly IRepository<OEconomyAdmin, string> _oeconomyAdminRepository;

		// 系统用户的领域服务
		private readonly UserPersonManager _userPersonManager;

		/// <summary>
		///【机构人员】机构人员变更领域
		/// </summary>
		private readonly IOEconomyPersonChangeManager _oeconomyPersonChangeManager;

		/// <summary>
		/// 【Parameter】参数的领域服务
		/// </summary>
		private readonly IParameterManager _parameterManager;

		/// <summary>
		/// 【承若书】电子印章授权领域服务
		/// </summary>
		private readonly IPledgeBookManager _pledgeBookManager;

		/// <summary>
		/// 【OEconomyPerson】的构造方法
		/// 通过构造函数注册服务到依赖注入容器中
		///</summary>
		public OEconomyPersonManager(
			IRepository<OEconomyPerson, string> oeconomypersonRepository,
			IRepository<OEconomyAdmin, string> oeconomyAdminRepository,
			IOEconomyPersonChangeManager oeconomyPersonChangeManager,
			IPledgeBookManager pledgeBookManager,
			IParameterManager parameterManager,
			UserPersonManager userPersonManager
		)
		{
			_oeconomypersonRepository = oeconomypersonRepository;
			_oeconomyAdminRepository = oeconomyAdminRepository;
			_oeconomyPersonChangeManager = oeconomyPersonChangeManager;
			_parameterManager = parameterManager;
			_userPersonManager = userPersonManager;
			_pledgeBookManager = pledgeBookManager;
		}

		#region -------------------------------------------------辅助工具生成---------------------------------------------- 

		/// <summary>
		/// 返回列表查询用
		/// </summary>
		/// <returns></returns>
		public IQueryable<OEconomyPerson> QueryEntityListAsNoTracking()
		{

			var query = _oeconomypersonRepository.GetAll().AsNoTracking()
						.Select(x => new OEconomyPerson
						{

							Id = x.Id,
							RYMC = x.RYMC,
							RYLX = x.RYLX,
							XB = x.XB,
							CSNY = x.CSNY,
							JG = x.JG,
							JTZZ = x.JTZZ,
							SFZH = x.SFZH,
							ZW = x.ZW,
							ZGZH = x.ZGZH,
							ZGZFZDW = x.ZGZFZDW,
							SGZH = x.SGZH,
							SGZFZDW = x.SGZFZDW,
							JYTS = x.JYTS,
							JYMJ = x.JYMJ,
							LXDH = x.LXDH,
							ZP = x.ZP,
							ZYPXJL = x.ZYPXJL,
							GZJL = x.GZJL,
							JGBH = x.JGBH,
							FZJGBH = x.FZJGBH,
							XLDM = x.XLDM,
							MZDM = x.MZDM,
							JSZCDM = x.JSZCDM,
							ZZMMDM = x.ZZMMDM,
							RYZT = x.RYZT,
							MM = x.MM,
							LRSJ = x.LRSJ,
							XLZH = x.XLZH,
							XLZCZH = x.XLZCZH,
							ZGZCZH = x.ZGZCZH,
							SGZYXQXQ = x.SGZYXQXQ,
							SGZYXQXZ = x.SGZYXQXZ,
							EKEYSN = x.EKEYSN,
							XGSJ = x.XGSJ,
							GZGW = x.GZGW,
							KWQ = x.KWQ,
							AJSPZT = x.AJSPZT,
							ZXSJ = x.ZXSJ,
							ZXRBH = x.ZXRBH,
							ZXYY = x.ZXYY,
							WQKTSJ = x.WQKTSJ,
							BASJ = x.BASJ,
							CAKEYSN = x.CAKEYSN,
							ZJLXDM = x.ZJLXDM,
							 PledgeBookID = x.PledgeBookID,
							  AccountID = x.AccountID,
						
						});
			return query;
		}

		/// <summary>
		/// 【OEconomyPerson】返回表达式数的实体信息即IQueryable类型
		/// </summary>
		/// <returns>IQueryable</returns>
		public IQueryable<OEconomyPerson> Query()
		{
			return _oeconomypersonRepository.GetAll();
		}
		/// <summary>
		/// 【OEconomyPerson】返回即IQueryable类型的实体，不包含EF Core跟踪标记
		/// </summary>
		/// <returns>IQueryable</returns>
		public IQueryable<OEconomyPerson> QueryAsNoTracking()
		{
			return _oeconomypersonRepository.GetAll().AsNoTracking();
		}
		/// <summary>
		/// 【OEconomyPerson】根据Id查询实体信息
		/// </summary>
		/// <param name="id"></param>
		/// <returns>实体</returns>
		public async Task<OEconomyPerson> FindByIdAsync(string id)
		{
			var entity = await _oeconomypersonRepository.GetAsync(id);
			return entity;
		}
		/// <summary>
		/// 【OEconomyPerson】检查实体是否存在
		/// </summary>
		/// <param name="id"></param>
		/// <returns>bool</returns>
		public async Task<bool> IsExistAsync(string id)
		{
			var result = await _oeconomypersonRepository.GetAll().AnyAsync(a => a.Id == id);
			return result;
		}
		/// <summary>
		/// 【OEconomyPerson】创建实体
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task<OEconomyPerson> CreateAsync(OEconomyPerson entity)
		{
			entity.Id = await _oeconomypersonRepository.InsertAndGetIdAsync(entity);
			return entity;
		}
		/// <summary>
		/// 【OEconomyPerson】更新实体
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task UpdateAsync(OEconomyPerson entity)
		{
			await _oeconomypersonRepository.UpdateAsync(entity);
		}
		/// <summary>
		/// 【OEconomyPerson】删除实体
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task DeleteAsync(string id)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _oeconomypersonRepository.DeleteAsync(id);
		}
		/// <summary>
		/// 【OEconomyPerson】批量删除
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task BatchDelete(List<string> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _oeconomypersonRepository.DeleteAsync(a => input.Contains(a.Id));
		}
		#endregion


		#region -------------------------------------------------用户自定义------------------------------------------------
		/*请在此扩展领域服务接口*/

		/// <summary>
		/// 【原始系统】获取机构人员编号
		/// </summary>
		/// <returns></returns>
		public object GetSequence()
		{
			var sql = string.Format("select {0}.Nextval from dual", "SEQ_CLFWQ_RYXX_RYBH");
			return _oeconomypersonRepository.GetDbContext().Database.ExecuteScalar(sql);
		}

		/// <summary>
		/// 【原始系统】获取新的人员编号
		/// </summary>
		/// <returns></returns>
		public string GetNewSequenceCode()
		{
			var code = this.GetSequence().ToString();
			return code.PadLeft(8, '0');
		}

		/// <summary>
		/// 通过关联查询获取列表查询结果
		/// </summary>
		/// <returns></returns>
		public IQueryable<OEconomyPerson> QueryUnionEntityListAsNoTracking()
		{
			// 这里目前必须要把类型查出来然后在联合查询
			var ListEntity = this._parameterManager.QueryPersonType().ToList();
			var CaseStatusList = this._parameterManager.QueryCaseStatus().ToList();
			var query = this.QueryEntityListAsNoTracking();
			
			var result = from x in query
						 select new OEconomyPerson
						 {
							 Id = x.Id,
							 RYMC = x.RYMC,
							 RYLX = x.RYLX,
							 XB = x.XB,
							 CSNY = x.CSNY,
							 JG = x.JG,
							 JTZZ = x.JTZZ,
							 SFZH = x.SFZH,
							 ZW = x.ZW,
							 ZGZH = x.ZGZH,
							 ZGZFZDW = x.ZGZFZDW,
							 SGZH = x.SGZH,
							 SGZFZDW = x.SGZFZDW,
							 JYTS = x.JYTS,
							 JYMJ = x.JYMJ,
							 LXDH = x.LXDH,
							 ZP = x.ZP,
							 ZYPXJL = x.ZYPXJL,
							 GZJL = x.GZJL,
							 JGBH = x.JGBH,
							 FZJGBH = x.FZJGBH,
							 XLDM = x.XLDM,
							 MZDM = x.MZDM,
							 JSZCDM = x.JSZCDM,
							 ZZMMDM = x.ZZMMDM,
							 RYZT = x.RYZT,
							 MM = x.MM,
							 LRSJ = x.LRSJ,
							 XLZH = x.XLZH,
							 XLZCZH = x.XLZCZH,
							 ZGZCZH = x.ZGZCZH,
							 SGZYXQXQ = x.SGZYXQXQ,
							 SGZYXQXZ = x.SGZYXQXZ,
							 EKEYSN = x.EKEYSN,
							 XGSJ = x.XGSJ,
							 GZGW = x.GZGW,
							 KWQ = x.KWQ,
							 AJSPZT = x.AJSPZT,
							 ZXSJ = x.ZXSJ,
							 ZXRBH = x.ZXRBH,
							 ZXYY = x.ZXYY,
							 WQKTSJ = x.WQKTSJ,
							 BASJ = x.BASJ,
							 CAKEYSN = x.CAKEYSN,
							 ZJLXDM = x.ZJLXDM,
							 AccountID = x.AccountID,
							 PledgeBookID = x.PledgeBookID,
							 // 联合查询属性
							 RYLXMC = EntityHelper.GetEntityParameter(ListEntity, x.RYLX).Value,
							 AJSPZTMC = EntityHelper.GetEntityParameter(CaseStatusList, x.AJSPZT).Value
						 };
			return result;
		}

		/// <summary>
		/// 提交经济机构人员信息（将状态为待提交的数据设置为待审核状态）
		/// </summary>
		/// <param name="OrganizeID">经济机构编号</param>
		/// <returns></returns>
		public async Task SubmitInitRecord(string OriginalNumber)
		{

			// 1. 获取我们机构下选择的所有机构人员
			var listPersonEntity = await this._oeconomyPersonChangeManager.Query()
				.Where(x => x.JGBH == OriginalNumber) // 获取当前机构
				.Where(x => x.AJSPZT == Const_Ajspzt.AJSPZT_BLRZ) // 状态 为办理入职 的人员
				.ToListAsync();

			// 2. 没有提交的人员全部设置为待审核
			foreach (var item in listPersonEntity)
			{
				// 如果原来的状态为
				item.RYZT = this.GetApprovalStatus(EApprovalStatus.WaitReview); // 设置为待审核
				await this._oeconomyPersonChangeManager.UpdateAsync(item);
				// 人员信息表中的RYXX中的实体
				var ryxxEntity = await this.FindByIdAsync(item.RYBH);
				ryxxEntity.AJSPZT = Const_Ajspzt.AJSPZT_BLRZ;//  状态 为办理入职 的人员
				ryxxEntity.JGBH = OriginalNumber;
				await this._oeconomypersonRepository.UpdateAsync(ryxxEntity);
				// 最后开通登录账号（如果账号不存在开通新账号）
				await this._userPersonManager.CreateOrUpdateAccountAsync(ryxxEntity);

			}
		}

		/// <summary>
		/// 指定的机构编号下增加人员
		/// </summary>
		/// <param name="OriginalNumber"></param>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task AcceptPerson(string OriginalNumber, string PersonID)
		{
			// 获取人员信息
			var personEntity = await this.FindByIdAsync(PersonID);
			// 人员实体转变更实体
			var personChangeEntity = this.ConvertToOEconomyPersonChange(personEntity);
			// 保存变更实体
			personChangeEntity.Id = this._oeconomyPersonChangeManager.GetNewSequenceCode();
			// 设置按键办理状态(办理入职)
			personChangeEntity.AJSPZT = Const_Ajspzt.AJSPZT_BLRZ;
			// 设置机构编号纳入我们机构
			personChangeEntity.JGBH = OriginalNumber;
			// 
			personChangeEntity.BGSJ = Clock.Now;
			// 创建一条变更数据
			await this._oeconomyPersonChangeManager.CreateAsync(personChangeEntity);

		}

		#endregion

		#region -------------------------------------------------判断逻辑------------------------------------------------

		/// <summary>
		/// 指定机构的人员是否存人员变更记录
		/// </summary>
		/// <param name="OriginalNumber"></param>
		/// <param name="PersonID"></param>
		/// <returns></returns>
		public Task<bool> IsExistPersonChange(string OriginalNumber, string PersonID)
		{
			return this._oeconomyPersonChangeManager.QueryAsNoTracking().AnyAsync(x => x.JGBH == OriginalNumber && x.RYBH == PersonID);
		}
		#endregion

		#region -------------------------------------------------机构管理员相关------------------------------------------------
		/// <summary>
		/// 指定机构编号下是否存在管理员账号（Zhxt）
		/// </summary>
		/// <param name="OriginalNumber"></param>
		/// <returns></returns>
		public async Task<bool> IsExistAdminAccount(string OriginalNumber)
		{
			return await this._oeconomyAdminRepository.GetAll().AnyAsync(x => x.Id == OriginalNumber);
		}

		/// <summary>
		/// 创建机构管理员(Zhxt)
		/// </summary>
		/// <param name="OEconomyAdmin"></param>
		/// <returns></returns>
		public async Task<OEconomyAdmin> GenerateAdminAccount(OEconomyAdmin OEconomyAdmin)
		{
			if (OEconomyAdmin.Id.IsNullOrEmpty())
			{
				OEconomyAdmin.Id = this.GetNewSequenceCode();
			}
			return await _oeconomyAdminRepository.InsertAsync(OEconomyAdmin);
		}

		/// <summary>
		/// 获取指定机构的管理员信息
		/// </summary>
		/// <param name="PersonID">人员编号，管理员编号</param>
		/// <returns></returns>
		public async Task<OEconomyAdmin> GetAdminPersonEntityAsync(string PersonID)
		{
			var personEntity =  await this._oeconomyAdminRepository.GetAsync(PersonID);

			return personEntity;
		}

		#endregion

		#region -------------------------------------------------新模式服务-承若书相关------------------------------------------------

		/// <summary>
		/// 查询关联了新模式中带承诺书的人员清单
		/// </summary>
		/// <returns></returns>
		public IQueryable<OEconomyPerson> QueryUnionEntityForBledgeBookListAsNoTracking()
		{
			var query = this.QueryUnionEntityListAsNoTracking();
			var queryBook = this._pledgeBookManager.QueryAsNoTracking();

			var result = from x in query
						 join b in queryBook on x.PledgeBookID equals b.Id into dc
						 from dci in dc.DefaultIfEmpty()
						 select new OEconomyPerson
						 {
							 Id = x.Id,
							 RYMC = x.RYMC,
							 RYLX = x.RYLX,
							 XB = x.XB,
							 CSNY = x.CSNY,
							 JG = x.JG,
							 JTZZ = x.JTZZ,
							 SFZH = x.SFZH,
							 ZW = x.ZW,
							 ZGZH = x.ZGZH,
							 ZGZFZDW = x.ZGZFZDW,
							 SGZH = x.SGZH,
							 SGZFZDW = x.SGZFZDW,
							 JYTS = x.JYTS,
							 JYMJ = x.JYMJ,
							 LXDH = x.LXDH,
							 ZP = x.ZP,
							 ZYPXJL = x.ZYPXJL,
							 GZJL = x.GZJL,
							 JGBH = x.JGBH,
							 FZJGBH = x.FZJGBH,
							 XLDM = x.XLDM,
							 MZDM = x.MZDM,
							 JSZCDM = x.JSZCDM,
							 ZZMMDM = x.ZZMMDM,
							 RYZT = x.RYZT,
							 MM = x.MM,
							 LRSJ = x.LRSJ,
							 XLZH = x.XLZH,
							 XLZCZH = x.XLZCZH,
							 ZGZCZH = x.ZGZCZH,
							 SGZYXQXQ = x.SGZYXQXQ,
							 SGZYXQXZ = x.SGZYXQXZ,
							 EKEYSN = x.EKEYSN,
							 XGSJ = x.XGSJ,
							 GZGW = x.GZGW,
							 KWQ = x.KWQ,
							 AJSPZT = x.AJSPZT,
							 ZXSJ = x.ZXSJ,
							 ZXRBH = x.ZXRBH,
							 ZXYY = x.ZXYY,
							 WQKTSJ = x.WQKTSJ,
							 BASJ = x.BASJ,
							 CAKEYSN = x.CAKEYSN,
							 ZJLXDM = x.ZJLXDM,

							 // 联合查询属性
							 RYLXMC = x.RYLXMC,
							 AJSPZTMC = x.AJSPZTMC,
							 PledgeBookID = x.PledgeBookID,
							 PledgeBook = dci
						 };


			return result;
		}

		#endregion

	}
}
